package com.itheima.jobs;

import com.itheima.common.RedisConst;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

public class ClearImageJob { //定义清理图片的任务

    @Autowired
    JedisPool jedisPool;

    private void clear() {
        System.out.println("启动一次");
        Set<String> imgNames  = jedisPool.getResource().smembers(RedisConst.SETMEAL_PIC_RESOURCES);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, 0);
        Date yesterday = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String str = sdf.format(yesterday);

        for (String imgName : imgNames) {
            System.out.println(imgName);
            System.out.println(str);
            if (imgName!=null && imgName.startsWith(str)) {
                delQiniu(imgName);

                jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES, imgName);
                System.out.println("删除了" + imgName + "图片!!");
            }
        }

    }

    private void delQiniu(String imgName) {
        Configuration cfg = new Configuration(Zone.zone2());

        String accessKey = "AnsdGV-d6vuDEMJ5-Wlodzcz7hKr3eKEWWs6vuSG";
        String secretKey = "16y6T5OT882AzEEFMjS8_9fJBPQqOdf_ZKFyOhEF";
        String bucket = "wodeqiniuyunkongjian";

        String key = imgName;

        Auth auth = Auth.create(accessKey, secretKey);

        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
